﻿using System;
using System.Collections.Specialized;
using System.Diagnostics;
using System.Globalization;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Runtime.Remoting;
using System.Security.Permissions;
using System.Web.UI;
using System.Web.UI.WebControls.WebParts;

using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;
using Microsoft.SharePoint.Security;
using Microsoft.SharePoint.Utilities;
using Microsoft.SharePoint.WebPartPages;

using EF;

namespace EF.vwpInspectuniquePerm
{
    public partial class vwpInspectuniquePermUserControl : UserControl
    {
        public bool _boolInspectWeb = false;
        public bool _boolInspectList = false;
        public bool _boolInspectLibrary = false;
        public bool _boolInspectFolder = false;
        public bool _boolInspectItem = false;
        public bool _boolInspectFile = false;

        protected void Page_Load(object sender, EventArgs e)
        {
            PanelMessage.Visible = false;
        }

        private void writeLog(string strMessage)
        {
            TextBoxMessage.Text += strMessage + @"<br />";
            EF.EFInspectUniquePerm.logTraceInfo(strMessage);
        }

        private void InspectFolder(SPFolder objSPFolder, bool boolRecover)
        {
            SPQuery objSPQuery = new SPQuery();
            objSPQuery.Query = "<OrderBy><FieldRef Name='ID'/></OrderBy>";
            objSPQuery.Folder = objSPFolder;
            SPWeb objSPWeb = objSPFolder.ParentWeb;
            SPList objSPList = objSPWeb.Lists[objSPFolder.ParentListId];

            if (_boolInspectFolder && objSPFolder.Item != null)
            {
                try
                {
                    if (objSPFolder.Item.HasUniqueRoleAssignments)
                    {
                        EFInspectUniquePerm.logObject(objSPWeb, objSPFolder);
                        if (boolRecover)
                        {
                            objSPFolder.Item.ResetRoleInheritance();
                        }
                    }
                }
                catch (Exception ex)
                {
                    PanelMessage.Visible = true;
                    writeLog(string.Format("InspectFolder(), objSPFolder.Url={0}", objSPFolder.Url));
                    writeLog(string.Format("InspectFolder(), ex.Message={0}", ex.Message));
                    writeLog(string.Format("InspectFolder(), ex.StackTrace={0}", ex.StackTrace));
                }
            }

            if (_boolInspectItem || _boolInspectFile)
            {
                SPListItemCollection objSPListItemCollection = objSPList.GetItems(objSPQuery);
                foreach (SPListItem objSPListItem in objSPListItemCollection)
                {
                    try
                    {
                        if (objSPListItem.HasUniqueRoleAssignments && objSPListItem.ContentType.Name != "Folder")
                        {
                            if (_boolInspectItem && objSPListItem.File == null)
                            {
                                EFInspectUniquePerm.logObject(objSPWeb, objSPListItem);
                                if (boolRecover)
                                {
                                    objSPListItem.ResetRoleInheritance();
                                }
                            }
                            if (_boolInspectFile && objSPListItem.File != null)
                            {
                                EFInspectUniquePerm.logObject(objSPWeb, objSPListItem.File);
                                if (boolRecover)
                                {
                                    objSPListItem.ResetRoleInheritance();
                                }
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        PanelMessage.Visible = true;
                        writeLog(string.Format("InspectFolder(), objSPListItem.Url={0}", objSPListItem.Url));
                        writeLog(string.Format("InspectFolder(), ex.Message={0}", ex.Message));
                        writeLog(string.Format("InspectFolder(), ex.StackTrace={0}", ex.StackTrace));
                    }
                }
            }

            SPFolderCollection objSPFolderCollection = objSPFolder.SubFolders;
            foreach (SPFolder objSPSubFolder in objSPFolderCollection)
            {
                InspectFolder(objSPSubFolder, boolRecover);
            }
        }

        private void InspectSubSite(SPWeb objSPWeb, bool boolRecover)
        {
            if (_boolInspectWeb)
            {
                if (objSPWeb.IsRootWeb == false && objSPWeb.HasUniqueRoleAssignments)
                {
                    EFInspectUniquePerm.logObject(objSPWeb);
                    if (boolRecover)
                    {
                        objSPWeb.ResetRoleInheritance();
                    }
                }
            }
            SPListCollection objSPListCollection = objSPWeb.Lists;
            foreach (SPList objSPList in objSPListCollection)
            {
                if (_boolInspectList || _boolInspectLibrary)
                {
                    try
                    {
                        if (objSPList.HasUniqueRoleAssignments)
                        {
                            if (_boolInspectLibrary && objSPList is SPDocumentLibrary)
                            {
                                SPDocumentLibrary objSPDocumentLibrary = (SPDocumentLibrary)objSPList;
                                EFInspectUniquePerm.logObject(objSPWeb, objSPDocumentLibrary);
                                if (boolRecover)
                                {
                                    objSPList.ResetRoleInheritance();
                                }
                            }
                            if (_boolInspectList && !(objSPList is SPDocumentLibrary))
                            {
                                EFInspectUniquePerm.logObject(objSPWeb, objSPList);
                                if (boolRecover)
                                {
                                    objSPList.ResetRoleInheritance();
                                }
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        PanelMessage.Visible = true;
                        writeLog(string.Format("InspectSubSite(), objSPList.RootFolder.Url={0}", objSPList.RootFolder.Url));
                        writeLog(string.Format("InspectSubSite(), ex.Message={0}", ex.Message));
                        writeLog(string.Format("InspectSubSite(), ex.StackTrace={0}", ex.StackTrace));
                    }
                }
                InspectFolder(objSPList.RootFolder, boolRecover);
            }

            SPWebCollection objSPWebCollection = objSPWeb.Webs;
            foreach (SPWeb objSPWebChild in objSPWebCollection)
            {
                InspectSubSite(objSPWebChild, boolRecover);
            }
        }

        private void ClearResults()
        {
            SPList splistResult = null;

            try
            {
                EFInspectUniquePerm._iWebCount = 0;
                EFInspectUniquePerm._iListCount = 0;
                EFInspectUniquePerm._iLibraryCount = 0;
                EFInspectUniquePerm._iFolderCount = 0;
                EFInspectUniquePerm._iItemCount = 0;
                EFInspectUniquePerm._iFileCount = 0;

                using (SPSite objSPSite = new SPSite(SPContext.Current.Site.ID))
                {
                    using (SPWeb objSPWebRoot = objSPSite.RootWeb)
                    {
                        objSPWebRoot.AllowUnsafeUpdates = true;
                        splistResult = objSPWebRoot.Lists.TryGetList(EFInspectUniquePerm.Result_ListTitle);
                        if (splistResult != null)
                        {
                            SPListItemCollection listItems = splistResult.Items;
                            int itemCount = listItems.Count;

                            for (int k = itemCount - 1; k >= 0; k--)
                            {
                                listItems.Delete(k);
                            }
                        }
                        objSPWebRoot.AllowUnsafeUpdates = false;
                    }
                }
            }
            catch (Exception ex)
            {
                PanelMessage.Visible = true;
                writeLog(string.Format("ClearResults(), ex.Message={0}", ex.Message));
                writeLog(string.Format("ClearResults(), ex.StackTrace={0}", ex.StackTrace));
            }
        }

        public void SearchObjects(bool boolRecover)
        {
            SPWeb objSPWeb = SPContext.Current.Web;

            _boolInspectWeb = CheckBoxListObjectType.Items[0].Selected;
            _boolInspectList = CheckBoxListObjectType.Items[1].Selected;
            _boolInspectLibrary = CheckBoxListObjectType.Items[2].Selected;
            _boolInspectFolder = CheckBoxListObjectType.Items[3].Selected;
            _boolInspectItem = CheckBoxListObjectType.Items[4].Selected;
            _boolInspectFile = CheckBoxListObjectType.Items[5].Selected;

            InspectSubSite(objSPWeb, boolRecover);

            EFInspectUniquePerm.logInfo(objSPWeb, objSPWeb.ServerRelativeUrl, EFInspectUniquePerm._iWebCount, EFInspectUniquePerm._iListCount, EFInspectUniquePerm._iLibraryCount, EFInspectUniquePerm._iFolderCount, EFInspectUniquePerm._iItemCount, EFInspectUniquePerm._iFileCount, boolRecover);
        }

        protected void LinkButtonSearch_Click(object sender, EventArgs e)
        {
            try
            {
                PanelMessage.Visible = false;

                SPLongOperation.BeginOperation beginOperation = null;

                if (beginOperation == null)
                {
                    beginOperation = delegate(SPLongOperation longOperation)
                    {
                        ClearResults();
                        SearchObjects(false);

                        longOperation.End(Request.RawUrl);
                    };
                }
                SPLongOperation.Begin(beginOperation);
            }
            catch (Exception ex)
            {
                PanelMessage.Visible = true;
                writeLog(string.Format("LinkButtonSearch_Click(), ex.Message={0}", ex.Message));
                writeLog(string.Format("LinkButtonSearch_Click(), ex.StackTrace={0}", ex.StackTrace));
            }
        }

        protected void LinkButtonRecover_Click(object sender, EventArgs e)
        {
            try
            {
                PanelMessage.Visible = false;

                SPLongOperation.BeginOperation beginOperation = null;

                if (beginOperation == null)
                {
                    beginOperation = delegate(SPLongOperation longOperation)
                    {
                        ClearResults();
                        SearchObjects(true);

                        longOperation.End(Request.RawUrl);
                    };
                }
                SPLongOperation.Begin(beginOperation);
            }
            catch (Exception ex)
            {
                PanelMessage.Visible = true;
                writeLog(string.Format("LinkButtonRecover_Click(), ex.Message={0}", ex.Message));
                writeLog(string.Format("LinkButtonRecover_Click(), ex.StackTrace={0}", ex.StackTrace));
            }
        }
    }
}
